/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 *
 */

import path from 'path';

import { expect } from '@jest/globals';

import { runHvigorAsync, runHvigorFailAsync } from '../../common/common';
import { commonFileOperation } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
  modulesOption: [ModuleTemplateType.SharedLibrary],
};

const testfun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();

  const entryModule = project.getModule('entry');
  const entryIndexEts = path.resolve(entryModule.moduleRootPath(), 'src', 'main', 'ets', 'pages', 'Index.ets');
  await commonFileOperation(entryIndexEts, async (json) => {
    return `
    @Entry
    @Component
    export struct Index {
      @State message: string = 'Hello World';
    
      build() {
        RelativeContainer() {
          Text(this.message)
            .id('HelloWorld')
            .onClick(() => {
              this.message = 'Welcome';
            })
        }
        .height('100%')
        .width('100%')
      }
    }
    `;
  });
  await commonFileOperation(path.resolve(projectRootPath, 'hvigorfile.ts'), async (json) => {
    return `
    import { appTasks } from '@ohos/hvigor-ohos-plugin';

    export default {
        system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
        plugins:{}         /* Custom plugin to extend the functionality of Hvigor. */
    }
    `;
  });
  await commonFileOperation(path.resolve(entryModule.moduleRootPath(), 'hvigorfile.ts'), async (json) => {
    return `
    import { hapTasks } from '@ohos/hvigor-ohos-plugin';
    import { HvigorLogger, getNode, hvigor } from "@ohos/hvigor";
    const log = HvigorLogger.getLogger('workerDispatcher');
    const node = getNode(__filename);
    hvigor.nodesEvaluated(() => {
      node.registerTask({
        name: "consoleHvigorLog",
        run() {
          console.log('111')
          log.info('info1')
          log.info('info2')
          log.warn('warn1')
          log.warn('warn2')
          // 这里的error不会阻塞构建，是正常场景，只需要关注位置就行
          log.error('error1')
          log.error('error2')
        },
        dependencies: ['default@PackageHap'],
        postDependencies: ['default@SignHap']
      })
    })
    export default {
      system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
      plugins: []         /* Custom plugin to extend the functionality of Hvigor. */
    }
    `;
  });

  const commands: string[] =
    'clean --mode module -p product=default -p module=entry@default assembleHap --analyze=normal --parallel --incremental --no-daemon'.split(' ');
  const result = await runHvigorAsync(projectRootPath, commands);
  record.addStep('1. 加入引起wanr、error的代码，构建', result);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
  expect(result.stdout).toContain('info1');
  expect(result.stdout).toContain('info2');
  expect(result.stderr).toContain('warn1');
  expect(result.stderr).toContain('warn2');
  expect(result.stderr).toContain('error1');
  expect(result.stderr).toContain('error2');
  expect(result.stderr).toContain('No signingConfigs profile is configured in current project');
  expect(result.stderr).toContain('invalid custom plugins config found');
  expect(result.stderr).toContain('It\'s not a recommended way to export struct with \'@Entry\' decorator, which may cause ACE Engine error in component preview mode.');

  const result1 = await runHvigorAsync(projectRootPath, [...commands, '--warn']);
  record.addStep('2. 编译参数加上--warn,构建', result1);
  expect(result1.stdout).not.toContain('info1');
  expect(result1.stdout).not.toContain('info2');
  expect(result1.stderr).toContain('warn1');
  expect(result1.stderr).toContain('warn2');
  expect(result1.stderr).toContain('No signingConfigs profile is configured in current project');
  expect(result1.stderr).toContain('invalid custom plugins config found');
  expect(result1.stderr).toContain('error1');
  expect(result1.stderr).toContain('error2');
  expect(result1.stderr).toContain('It\'s not a recommended way to export struct with \'@Entry\' decorator, which may cause ACE Engine error in component preview mode.');

  const result2 = await runHvigorAsync(projectRootPath, [...commands, '--error']);
  record.addStep('3. 编译参数加上--error,构建', result2);
  expect(result2.stdout).not.toContain('info1');
  expect(result2.stdout).not.toContain('info2');
  expect(result2.stderr).not.toContain('warn1');
  expect(result2.stderr).not.toContain('warn2');
  expect(result2.stderr).not.toContain('No signingConfigs profile is configured in current project');
  expect(result2.stderr).not.toContain('invalid custom plugins config found');
  expect(result2.stderr).toContain('error1');
  expect(result2.stderr).toContain('error2');
  expect(result2.stderr).not.toContain('It\'s not a recommended way to export struct with \'@Entry\' decorator, which may cause ACE Engine error in component preview mode.');

  await commonFileOperation(entryIndexEts, async (json) => {
    return `
    @Entry
    @Component
    export struct Index {
      @State message: string = 'Hello World';
    
      build() {
        RelativeContainer() {
          Text(this.message)
            .id('HelloWorld')123
            .onClick(() => {
              this.message = 'Welcome';
            })
        }
        .height('100%')
        .width('100%')
      }
    }
    `;
  });
  const result3 = await runHvigorFailAsync(projectRootPath, commands);
  record.addStep('4. 加上会导致error且阻塞构建的代码,构建', result3);
  expect(result3.stdout).not.toContain('It\'s not a recommended way to export struct with \'@Entry\' decorator, which may cause ACE Engine error in component preview mode.');
  expect(result3.stderr).toContain('It\'s not a recommended way to export struct with \'@Entry\' decorator, which may cause ACE Engine error in component preview mode.');
  expect(result3.stderr).toContain('Property \'onClick\' does not exist on type \'123\'');

  const result4 = await runHvigorFailAsync(projectRootPath, [...commands, '--warn']);
  record.addStep('5. 编译参数加上--warn,构建', result4);
  expect(result4.stdout).not.toContain('It\'s not a recommended way to export struct with \'@Entry\' decorator, which may cause ACE Engine error in component preview mode.');
  expect(result4.stderr).toContain('It\'s not a recommended way to export struct with \'@Entry\' decorator, which may cause ACE Engine error in component preview mode.');
  expect(result4.stderr).toContain('Property \'onClick\' does not exist on type \'123\'');

  const result5 = await runHvigorFailAsync(projectRootPath, [...commands, '--error']);
  record.addStep('5. 编译参数加上--error,构建', result5);
  expect(result5.stdout).not.toContain('It\'s not a recommended way to export struct with \'@Entry\' decorator, which may cause ACE Engine error in component preview mode.');
  expect(result5.stderr).not.toContain('It\'s not a recommended way to export struct with \'@Entry\' decorator, which may cause ACE Engine error in component preview mode.');
  expect(result5.stderr).toContain('Property \'onClick\' does not exist on type \'123\'');
};

TestCaseBuilder.builder()
  .caseName('LOGGER_PRINT_INFOPOSITION')
  .description('看护基础的info、warn、error的打印位置')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L0).build())
  .testFun(testfun)
  .load();
